<template>
  <div class="SNWGJADD">
    <div class="list">
      <van-form validate-first>
        <div v-for="(item, index) in labelData" :key="index">
          <!-- <span style="color: #ff0000">*</span> -->
          <van-field required v-if="!item.isSelect && !item.isTime" :readonly="item.isread" v-model="formData[item.key]" :label="item.label" :placeholder="'请填写' + item.label" />
          <div v-if="item.isSelect && !item.isTime">
            <div v-if="item.label !== '常住地址' && item.label !== '注册区域'">
              <van-field readonly required clickable name="picker" v-model="formData[item.key]" :label="item.label" :placeholder="'请选择' + item.label" @click="formData1[item.key1] = true" />
              <van-popup v-model="formData1[item.key1]" position="bottom" get-container="#popup">
                <van-picker show-toolbar :columns="formData2[item.key1]" value-key="DICNAME" @confirm="onConfirm1" @cancel="formData1[item.key1] = false" />
              </van-popup>
            </div>
            <span class="btn" v-if="item.label == '常住地址'">
              <van-field required readonly clickable name="picker" v-model="formData[item.key]" :label="item.label" :placeholder="'请选择' + item.label" @click="handleChange" />
              <van-popup v-model="IsShowAre" round position="bottom">
                <van-cascader v-model="cascaderValue" title="切换城市" :options="options" @close="closeA" @change="onChange" @finish="onFinish" />
              </van-popup>
            </span>
            <span class="btn" v-if="item.label == '注册区域'">
              <van-field required readonly clickable name="picker" v-model="formData[item.key]" :label="item.label" :placeholder="'请选择' + item.label" @click="handleChange1" />
              <van-popup v-model="IsShowAre1" round position="bottom">
                <van-cascader v-model="cascaderValue" title="切换城市" :options="options" @close="closeA1" @change="onChange1" @finish="onFinish" />
              </van-popup>
            </span>
          </div>
          <div v-if="item.isTime">
            <van-field required readonly clickable name="picker" @click="formData1[item.key1] = true" v-model="formData[item.key]" :label="item.label" :placeholder="'请选择' + item.label" />
            <van-popup v-model="formData1[item.key1]" position="bottom">
              <van-datetime-picker v-model="currentDate" type="date" title="选择年月日" @cancel="formData1[item.key1] = false" @confirm="onConfirm2" :min-date="minDate" :max-date="maxDate" />
            </van-popup>
          </div>
        </div>
      </van-form>
    </div>
    <div class="footer">
      <van-button type="info" size="normal" style="padding: 6px; width: 90vw" @click="getinsertDataView('修改')">保存</van-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.SNWGJADD {
  height: 54vh;
  width: 100%;
  overflow-y: auto;
  padding: 6px;
  position: relative;

  .list {
    height: 50vh;
    overflow-y: auto;
  }

  .footer {
    position: absolute;
    //   height: 6vh;
    // bottom: 18px;
    left: 50%;
    top: 94%;
    transform: translate(-50%, -50%);
  }
}
</style>

<script>
import { GetAdministrative, getDatalistForTree, zhejiangHouseArtisan, zhejiangHouseArtisanUp, ossUploadFiles, FileServerProxy } from '../../utils/api'
import { Dialog } from 'vant'
export default {
  data() {
    return {
      formData: {
        citycode: '',
        artisanName: '',
        idCard: '',
        phone: '',
        belongArea: '',
        belongCountry: '',
        contactAddress: '',
        setTime: '',
        inProvince: '',
        farmerAdd: 1
      },
      show: false,
      isInProvince: '',
      actions: [
        {
          name: '选项'
        },
        {
          name: '选项'
        },
        {
          name: '选项',
          subname: '描述信息',
          openType: 'share'
        }
      ],
      cascaderValue: '',
      options: [
        {
          text: '',
          value: '',
          children: []
        }
      ],
      IsShowAre: false,
      IsShowAre1: false,
      showEdition: true,
      currentDate: new Date(),
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(2089, 12, 1),
      isread: false,
      formData1: {
        sex: false,
        artisanEducation: false,
        CSNY: false,
        setTime: false,
        inProvince: false
      },
      formData2: {
        inProvince: [
          {
            DICID: 1,
            DICNAME: '是',
            key: 'inProvince'
          },
          {
            DICID: 0,
            DICNAME: '否',
            key: 'inProvince'
          }
        ],
        artisanEducation: [
          {
            DICNAME: '初中及以下',
            key: 'artisanEducation'
          },
          {
            DICNAME: '高中',
            key: 'artisanEducation'
          },
          {
            DICNAME: '大专',
            key: 'artisanEducation'
          },
          {
            DICNAME: '本科',
            key: 'artisanEducation'
          },
          {
            DICNAME: '研究生',
            key: 'artisanEducation'
          }
        ]
      },
      fileList: [],
      url: '',
      isGOTo1: false,
      baseUrl: window.g.BaseURL,
      belongAreas: '',
      belongCountrys: '',
      qitaShow: false,
      labelData: [
        {
          label: '工匠姓名',
          key: 'artisanName',
          isSelect: false,
          isread: false
        },
        {
          label: '身份证号',
          key: 'idCard',
          isread: false
        },
        {
          label: '联系电话',
          key: 'phone',
          isread: false
        },
        {
          label: '注册区域',
          key: 'belongArea',
          isSelect: true,
          isread: false
        },
        {
          label: '常住地址',
          key: 'contactAddress',
          isSelect: true,
          isread: false
        },
        {
          label: '入驻时间',
          key: 'setTime',
          key1: 'setTime',
          isread: true,
          isTime: true
        },
        {
          label: '是否是省内工匠',
          key: 'inProvince',
          key1: 'inProvince',
          isSelect: true,
          isread: true
        }
      ]
    }
  },
  mounted() {
    if (ZWJSBridge) {
      ZWJSBridge.setTitle({
        title: '新增工匠'
      })
        .then((res) => {})
        .catch((err) => {})
    }
    //this.getGJInformcion()
    this.getXianOpenDataView()
  },
  methods: {
    //获取上传的图片回显
    async getPhoto(data1) {
      this.fileList = []
      // let data = res.data.data[0]
      this.url = 'api/upload/oss/preview?fileId=' + data1
      this.fileList.push({
        url: this.baseUrl + 'api/upload/oss/preview?fileId=' + data1,
        isImage: true
      })
    },
    onClose() {
      this.setData({ show: false })
    },

    onSelect(event) {
      console.log(event.detail)
    },
    //获取工匠信息
    async getGJInformcion() {
      debugger
      let data = {
        accessCode: 'd6158bcf5e1c4a079375143b67b311f3',
        cityCode: '441300000000',
        id: window.localStorage.getItem('DanDianid') || ''
      }
      const res = await zhejiangHouseArtisan(data)
    },
    onConfirm1(value) {
      debugger
      console.log(value, 'bfui')
      this.formData1[value.key] = false
      this.formData[value.key] = value.DICNAME
      this.isInProvince = value.DICID
    },
    getXianOpenDataView: async function (data = '330000000000') {
      this.options = []
      const res = await getDatalistForTree(data)
      res.data.data.forEach((item) => {
        this.options.push({
          text: item.cityname,
          value: item.citycode,
          children: []
        })
      })
      console.log(this.options, 'hezhilong')
      // this.options = res.data.data
    },
    handleChange() {
      this.IsShowAre = true
    },
    handleChange1() {
      this.IsShowAre1 = true
    },
    onChange({ value, selectedOptions, tabIndex }) {
      if (selectedOptions[tabIndex].children.length == 0 && tabIndex < 2) {
        this.getXZQH(value, selectedOptions, tabIndex)
      }
      this.onFinish({ value, selectedOptions, tabIndex })
    },
    onChange1({ value, selectedOptions, tabIndex }) {
      if (selectedOptions[tabIndex].children.length == 0 && tabIndex < 2) {
        this.getXZQH(value, selectedOptions, tabIndex)
      }
      this.onFinish1({ value, selectedOptions, tabIndex })
    },
    closeA() {
      this.IsShowAre = false
    },
    closeA1() {
      this.IsShowAre1 = false
    },
    onFinish({ value, selectedOptions, tabIndex }) {
      debugger
      this.formData.contactAddress = selectedOptions.map((option) => option.text).join('')
      //this.formData.citycode=value;
      this.areaCode = selectedOptions.map((option) => option.value)
      this.areaCode.length == 3 ? (this.IsShowAre = false) : ''
    },
    onFinish1({ value, selectedOptions, tabIndex }) {
      debugger
      this.formData.belongArea = selectedOptions.map((option) => option.text).join('/')
      if (selectedOptions && selectedOptions.length == 1) {
        this.belongAreas = selectedOptions[0].text
      }
      if (selectedOptions && selectedOptions.length == 2) {
        this.belongCountrys = selectedOptions[1].text
      }
      this.formData.citycode = value
      this.areaCode = selectedOptions.map((option) => option.value)
      this.areaCode.length == 3 ? (this.IsShowAre = false) : ''
    },
    getXZQH: async function (value, selectedOptions, tabIndex) {
      var res = await GetAdministrative(value)
      selectedOptions[tabIndex].children = []
      if (res.data.data.length > 0) {
        res.data.data.forEach((element) => {
          let obj = {
            text: element.cityname,
            value: element.citycode
          }
          if (tabIndex < 1) {
            obj['children'] = []
          }
          selectedOptions[tabIndex].children.push(obj)
        })
      }
    },
    onConfirm2(value) {
      this.formData.setTime = this.dateFormat(value)
      this.formData1.setTime = false
    },
    // 格式化日期
    dateFormat(val) {
      let year = val.getFullYear()
      let month = val.getMonth() + 1
      let day = val.getDate()
      let hour = val.getHours()
      let minute = val.getMinutes()
      if (month >= 1 && month <= 9) {
        month = `0${month}`
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`
      }
      let time = `${year}-${month}-${day}  ${hour}:${minute}:00`
      return time
    },
    isEmpty(obj) {
      if (typeof obj === 'undefined' || obj === null || obj === '' || obj === 'null') return true
      return false
    },
    preProcessData(data) {
      Object.keys(data).forEach((item) => {
        if (this.isEmpty(data[item])) {
          delete data[item]
        }
      })
      return data
    },
    //根据身份证查询户主户籍姓名和身份证匹配
    async handleMatching(data, data1) {
      let params = {
        accessCode: '4f54f932615d11ec87416805cab640a0',
        cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
        params: { czrkgmsfhm: data }
      }
      const res = await FileServerProxy(params)
      try {
        if (res.data.datas == null) {
          this.isGOTo1 = false
          //this.$toast.fail('未查到当前填写的申请人姓名和身份证号码!')
          Dialog.confirm({
            message: `未查到当前填写的申请人姓名和身份证号码,是否继续提交保存工匠信息?`
          }).then((res) => {
            this.saveOrUpdateCraf()
          })
        } else {
          res.data.datas.forEach((item) => {
            if (item.ELC_LICENCE_STRUCT.DATA.CZRKGMSFHM == data) {
              if (item.ELC_LICENCE_STRUCT.DATA.CZRKXM == data1) {
                this.saveOrUpdateCraf()
              } else {
                //this.$toast.fail('当前填写的代办申请人姓名和身份证号码不匹配!')
                Dialog.confirm({
                  message: `当前填写的代办申请人姓名和身份证号码不匹配,是否继续提交保存工匠信息?`
                }).then((res) => {
                  this.saveOrUpdateCraf()
                })
                this.isGOTo1 = false
              }
            }
          })
        }
      } catch (err) {
        this.isGOTo1 = true
      }
    },
    validator(val) {
      var idcardReg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
      return idcardReg.test(val)
    },
    //保存工匠基本信息
    async saveOrUpdateCraf() {
      this.formData = this.preProcessData(this.formData)
      //需要先判断技能中是否有其他字段 如果有并且更新了需要同步更新workerType
      try {
        var newArr = this.formData.workerType == null ? [] : this.formData.workerType.split(',')
        var xiabiao = newArr.indexOf('其他')
        if (xiabiao > -1) newArr[xiabiao] = this.formData.otherSkill
      } catch (err) {
        console.log(err)
      }
      this.formData.workerType = newArr.toString()
      this.formData.inProvince = this.isInProvince
      this.formData.belongArea = this.belongAreas
      this.formData.belongCountry = this.belongCountrys
      var newobj = this.formData
      let data1 = {
        accessCode: 'd6158bcf5e1c4a079375143b67b311f3',
        appKey: '6738b790-69e8-11ec-a673-6805cab640a0',
        cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
        id: window.localStorage.getItem('DanDianid') || '',
        houseArtisanInfo: newobj
      }
      const res = await zhejiangHouseArtisanUp(data1)
      if (res.data && res.data.data) {
        this.$toast.success('工匠添加成功!')
        window.sessionStorage.setItem('addGJ', 1)
        this.$store.commit('getGJQY', newobj)
        let rowGuid1 = JSON.parse(window.sessionStorage.getItem('fileData'))
        if (rowGuid1?.S) {
          this.$router.push({
            path: '/fileData'
          })
        } else {
          this.$router.push({
            path: 'ChooseCraftsman'
          })
        }
      }
    },
    async getinsertDataView(data) {
      //都是必填
      debugger
      let me = this
      console.log(me.formData, me.belongAreas, me.belongCountrys, me.isInProvince)
      if (!me.belongCountrys) {
        this.$toast.fail('注册区域只能到区县!')
        return false
      }
      if (me.formData.artisanName && me.belongAreas && me.formData.contactAddress && (me.isInProvince == 0 || me.isInProvince == 1) && me.formData.idCard && me.formData.setTime) {
      } else {
        this.$toast.fail('请填写必填项!')
        return false
      }
      let istrue = this.validator(this.formData.idCard)
      if (!istrue) {
        this.$toast.fail('填写的身份证号不符合规范')
      }
      //wjh 2023-09-27 逻辑重新写  先判断是不是省内  省内掉大数据查询  省外的不用掉大数据接口   没查到给提示 但是继续保存或者修改    farmerAdd  1是省内  0是省外
      if (this.isInProvince == 0) {
        //直接保存
        this.saveOrUpdateCraf()
      } else {
        //省内 掉大数据接口查询
        this.handleMatching(this.formData.idCard, this.formData.artisanName)
      }

      // if (!this.isGOTo1) {
      //   this.$confirm({
      //     title: '提示',
      //     message: '是否添加省外工匠？',
      //     btn: {
      //       okText: '确定',
      //       cancelText: '取消'
      //     }
      //   })
      //     .then(() => {
      //       // do something
      //       this.formData.inProvince = '否'
      //     })
      //     .catch(() => {
      //       console.log('no')
      //     })
      // } else {
      //   this.formData.inProvince = '是'
      // }
      // this.formData = this.preProcessData(this.formData)
      // //需要先判断技能中是否有其他字段 如果有并且更新了需要同步更新workerType
      // try {
      //   var newArr = this.formData.workerType == null ? [] : this.formData.workerType.split(',')
      //   var xiabiao = newArr.indexOf('其他')
      //   if (xiabiao > -1) newArr[xiabiao] = this.formData.otherSkill
      // } catch (err) {
      //   console.log(err)
      // }
      // this.formData.workerType = newArr.toString()
      // var newobj = this.formData
      // console.log(newobj, 'klkopl')
      // if (data == '修改') {
      //   //只能修改
      //   let data1 = {
      //     accessCode: 'd6158bcf5e1c4a079375143b67b311f3',
      //     appKey: '6738b790-69e8-11ec-a673-6805cab640a0',
      //     cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
      //     id: window.localStorage.getItem('DanDianid') || '',
      //     houseArtisanInfo: newobj
      //   }
      //   const res = await zhejiangHouseArtisanUp(data1)
      //   if (res.data.code == 200 && res.data.msg == '成功') {
      //     this.$toast.success('工匠添加成功!')
      //     this.$store.commit('getGJQY', newobj)
      //     this.$router.push({
      //       path: '/fileData'
      //     })
      //   }
      // }
    },
    afterRead(file) {
      this.getFileServerUpload(file.file, 'scsfz')
    },
    getFileServerUpload: async function (file, data) {
      let formData = new FormData()
      formData.append('files', file)
      formData.append('path', 'gj')
      formData.append('groupName', '工匠信息')
      formData.append('toGroupGuid', '123')
      const res = await ossUploadFiles(formData)
      let data2 = res.data.data
      console.log(data2, 'hezhilong')
      this.formData.fileid = data2[0].id
      if (this.formData.fileid) {
        this.$toast.success('上传成功!')
      }
    },
    delectFile: async function (file) {
      debugger
      try {
        let fileguid = ''
        if (file.ROW_GUID) {
          fileguid = file.ROW_GUID
        } else {
          fileguid = this.formData.fileid
        }
        this.url = ''
        console.log(fileguid, 'dkjfhui')
        if (fileguid) {
          let params = {
            accessCode: 'ce9b691634de4ebca68dc5bb638d07f4',
            cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
            params: {
              fileGuid: fileguid,
              token: window.localStorage.getItem('token')
            }
          }
          const res = await FileServerProxy(params)
          let data = JSON.parse(res.data.data).Success
          if (data) {
            this.$toast.success('删除成功!')
          }
        }
      } catch (err) {
        this.$toast.success('删除成功!')
      }
    }
  }
}
</script>
